package com.ohuang.apkMerge

import com.google.gson.Gson
import java.io.File


fun outReplaceConfig(path: String) {
    var hashMap = HashMap<String, String>()
    hashMap["androidx/recyclerview"] = "oh/recyclerview"
    hashMap["xxxxx"] = "yyyy/tttt"


    var hashMap2 = HashMap<String, String>()
    hashMap2["androidx.recyclerview"] = "oh.recyclerview"
    hashMap2["androidx.activity"] = "oh.activity"

    var replaceConfig = ReplaceConfig(hashMap, hashMap2)
    var gson = Gson()
    var toJson = gson.toJson(replaceConfig)
    writeText(File("$path/ReplaceConfig.json"), toJson)
}

fun copyAndChangeFrameWorkPackageName(
    path: String,
    path2: String,
    jsonPath: String
) {
    var readText = readText(File(jsonPath))
    var gson = Gson()
    var fromJson = gson.fromJson(readText, ReplaceConfig::class.java)
    copyAndChangeFrameWorkPackageName(path, path2, fromJson.smaliMap,fromJson.layoutMap)
}

/**
 * 修改apk第三库包名
 * smalimap smali文件和包名路径的替换规则
 * layoutMap  布局的View的包名替换规则
 */
fun copyAndChangeFrameWorkPackageName(
    path: String,
    path2: String,
    smaliMap: Map<String, String>,
    layoutMap: Map<String, String>
) {
    var currentTimeMillis = System.currentTimeMillis()


    File(path).listFiles()?.forEach {
        if (it.name == "res") {
            return@forEach
        }
        if (it.name.startsWith("smali")) {
            return@forEach
        }
        if(it.name=="AndroidManifest.xml"){
            copyAndReplaceFile(it.absolutePath, path2 + "/${it.name}", layoutMap)
            return@forEach
        }
        println("---开始复制${it.name}---")
        copyPathAllFile("$path/${it.name}", "$path2/${it.name}")
    }
    println("---开始复制res---")
    File("$path/res").listFiles()?.forEach {
        val targetPath = "$path2/res"
        if (it.isDirectory) {
            println("--------开始复制${it.name}-------")
            if (it.name.startsWith("layout")) {
                copyReplaceLayout(it.absolutePath, targetPath + "/${it.name}", map = layoutMap)
            } else {
                copyPathAllFile(it.absolutePath, targetPath + "/${it.name}")
            }

        }
    }
    copyAndChangePackageName(path, path2, replaceMap = smaliMap)
    println("复制 用时：" + (System.currentTimeMillis() - currentTimeMillis) / 1000 + "s")
}


/**
 * 布局包名替换
 */
fun copyReplaceLayout(path: String, path2: String, map: Map<String, String>) {
    var file = File(path2)
    if (!file.exists()) {
        file.mkdirs()
    }
    File(path).listFiles()?.forEach {

        if (it.isFile) {
            copyAndReplaceFile(it.absolutePath, path2 + "/${it.name}", map)
        }

    }
}



